<template>
  <div class="user-management container my-4">
    <!-- 工具栏 -->
    <div class="row mb-3 align-items-center">
      <div class="col-md-6 mb-2 mb-md-0">
        <div class="input-group">
          <span class="input-group-text"><i class="bi bi-search"></i></span>
          <input type="text" class="form-control" v-model="searchQuery" placeholder="搜索账号（owner_id）" />
        </div>
      </div>
      <div class="col-md-6 text-md-end">
        <button class="btn btn-primary" @click="openAddUserModal">
          <i class="bi bi-plus-lg me-2"></i>新增用户
        </button>
      </div>
    </div>

    <!-- 用户表格 -->
    <div class="table-responsive">
      <table class="table table-bordered table-hover">
        <thead class="table-light">
          <tr>
            <th>ID</th>
            <th>账号（owner_id）</th>
            <th>姓名</th>
            <th>职位</th>
            <th>手机号</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in filteredUsers" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.owner_id }}</td>
            <td>{{ user.name }}</td>
            <td>{{ user.role_name }}</td>
            <td>{{ user.phone }}</td>
            <td>
              <button class="btn btn-warning btn-sm me-2" @click="handleEditUser(user)">编辑</button>
              <button class="btn btn-danger btn-sm" @click="handleDeleteUser(user.id)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 用户模态框 -->
    <div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true" ref="userModalRef">
      <div class="modal-dialog">
        <div class="modal-content">
          <form @submit.prevent="dialogMode === 'add' ? submitAddUser() : submitEditUser()">
            <div class="modal-header">
              <h5 class="modal-title" id="userModalLabel">{{ dialogMode === 'add' ? '新增用户' : '编辑用户' }}</h5>
              <button type="button" class="btn-close" @click="closeModal"></button>
            </div>
            <div class="modal-body">
              <div class="mb-3">
                <label for="owner_id" class="form-label">账号（owner_id）</label>
                <input type="text" class="form-control" id="owner_id" v-model="editUser.owner_id" :disabled="dialogMode === 'edit'" required />
                <div v-if="errors.owner_id" class="text-danger">{{ errors.owner_id }}</div>
              </div>
              <div class="mb-3">
                <label for="name" class="form-label">姓名</label>
                <input type="text" class="form-control" id="name" v-model="editUser.name" required />
                <div v-if="errors.name" class="text-danger">{{ errors.name }}</div>
              </div>
              <div class="mb-3" v-if="dialogMode === 'add'">
                <label for="password" class="form-label">密码</label>
                <input type="password" class="form-control" id="password" v-model="editUser.password" required />
                <div v-if="errors.password" class="text-danger">{{ errors.password }}</div>
              </div>
              <div class="mb-3">
                <label for="role_id" class="form-label">职位</label>
                <select class="form-control" id="role_id" v-model.number="editUser.role_id" required>
                  <option value="">请选择职位</option>
                  <option :value="1">管理员</option>
                  <option :value="2">业主</option>
                </select>
                <div v-if="errors.role_id" class="text-danger">{{ errors.role_id }}</div>
              </div>
              <!-- 仅在角色为业主时显示 -->
              <div v-if="editUser.role_id === 2">
                <div class="mb-3">
                  <label for="floor" class="form-label">楼层</label>
                  <input type="number" class="form-control" id="floor" v-model.number="editUser.floor" required />
                  <div v-if="errors.floor" class="text-danger">{{ errors.floor }}</div>
                </div>
                <div class="mb-3">
                  <label for="room_count" class="form-label">房间数</label>
                  <input type="number" class="form-control" id="room_count" v-model.number="editUser.room_count" required />
                  <div v-if="errors.room_count" class="text-danger">{{ errors.room_count }}</div>
                </div>
              </div>
              <div class="mb-3">
                <label for="phone" class="form-label">手机号</label>
                <input type="text" class="form-control" id="phone" v-model="editUser.phone" />
                <div v-if="errors.phone" class="text-danger">{{ errors.phone }}</div>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary">提交</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { ref, computed, onMounted, watch } from "vue";
import { Modal } from "bootstrap";

export default {
  name: "UserManagement",
  setup() {
    const token = localStorage.getItem("token");
    const users = ref([]);
    const searchQuery = ref("");
    const dialogMode = ref("add");
    const editUser = ref({
      id: null,
      owner_id: "",
      name: "",
      password: "",
      role_id: "",
      phone: "",
      floor: null,
      room_count: null,
    });
    const userModalRef = ref(null);
    const errors = ref({});

    // 过滤后的用户列表
    const filteredUsers = computed(() =>
      users.value.filter((user) =>
        user.owner_id?.toLowerCase().includes(searchQuery.value.toLowerCase())
      )
    );

    // 获取所有用户数据
    const fetchData = async () => {
      try {
        const response = await axios.get("http://localhost:3008/users", {
          headers: { Authorization: `Bearer ${token}` },
        });
        users.value = response.data.data;
      } catch (error) {
        console.error("获取用户数据失败：", error);
        alert(`获取用户数据失败：${error.response?.data?.message || error.message}`);
      }
    };

    // 显示模态框
    const showModal = () => {
      const modalInstance = new Modal(userModalRef.value);
      modalInstance.show();
    };

    // 关闭模态框
    const closeModal = () => {
      const modalInstance = Modal.getInstance(userModalRef.value);
      modalInstance.hide();
      resetForm();
    };

    // 打开新增用户模态框
    const openAddUserModal = () => {
      dialogMode.value = "add";
      editUser.value = { id: null, owner_id: "", name: "", password: "", role_id: "", phone: "", floor: null, room_count: null };
      showModal();
    };

    // 打开编辑用户模态框
    const handleEditUser = (user) => {
      dialogMode.value = "edit";
      editUser.value = { ...user };
      showModal();
    };

    // 提交新增用户
    const submitAddUser = async () => {
      if (!validateForm()) return;
      try {
        const payload = {
          name: editUser.value.name,
          password: editUser.value.password,
          role_id: editUser.value.role_id,
          phone: editUser.value.phone || null,
          owner_id: editUser.value.owner_id,
          unit_id: null,
          floor: editUser.value.role_id === 2 ? editUser.value.floor : 0, 
          room_count: editUser.value.role_id === 2 ? editUser.value.room_count : 0, 
        };
        const response = await axios.post(
          "http://localhost:3008/users",
          payload,
          { headers: { Authorization: `Bearer ${token}` } }
        );
        if (response.data.message === "用户添加成功") {
          alert("用户添加成功");
          fetchData(); 
          closeModal();
        }
      } catch (error) {
        console.error("添加用户失败：", error);
        alert(`添加用户失败：${error.response?.data?.message || error.message}`);
      }
    };

    // 提交编辑用户
    const submitEditUser = async () => {
      if (!validateForm()) return;
      try {
        const payload = {
          name: editUser.value.name,
          phone: editUser.value.phone || null,
          role_id: editUser.value.role_id,
          owner_id: editUser.value.owner_id, 
          floor: editUser.value.role_id === 2 ? editUser.value.floor : 0, 
          room_count: editUser.value.role_id === 2 ? editUser.value.room_count : 0, 
        };
        const response = await axios.patch(
          `http://localhost:3008/users/${editUser.value.id}`,
          payload,
          { headers: { Authorization: `Bearer ${token}` } }
        );
        if (response.data.message === "用户资料更新成功") {
          alert("用户更新成功");
          fetchData();
          closeModal();
        }
      } catch (error) {
        console.error("编辑用户失败：", error);
        alert(`编辑用户失败：${error.response?.data?.message || error.message}`);
      }
    };

    // 删除用户
    const handleDeleteUser = async (userId) => {
      if (!confirm("确定要删除这个用户吗？")) return;
      try {
        const response = await axios.delete(
          `http://localhost:3008/users/${userId}`,
          { headers: { Authorization: `Bearer ${token}` } }
        );
        if (response.data.message === "用户删除成功") {
          alert("用户删除成功");
          fetchData();
        }
      } catch (error) {
        console.error("删除用户失败：", error);
        alert(`删除用户失败：${error.response?.data?.message || error.message}`);
      }
    };

    // 表单验证
    const validateForm = () => {
      errors.value = {};
      let valid = true;

      if (!editUser.value.owner_id) {
        errors.value.owner_id = "请输入账号（owner_id）";
        valid = false;
      }

      if (!editUser.value.name) {
        errors.value.name = "请输入姓名";
        valid = false;
      }

      if (dialogMode.value === "add" && !editUser.value.password) {
        errors.value.password = "请输入密码";
        valid = false;
      }

      if (!editUser.value.role_id) {
        errors.value.role_id = "请选择职位";
        valid = false;
      }

      if (editUser.value.role_id === 2) { // 仅对业主用户验证
        if (editUser.value.floor === null || editUser.value.floor === undefined) {
          errors.value.floor = "请输入楼层";
          valid = false;
        }
        if (editUser.value.room_count === null || editUser.value.room_count === undefined) {
          errors.value.room_count = "请输入房间数";
          valid = false;
        }
      }

      if (editUser.value.phone && !/^\d{10,15}$/.test(editUser.value.phone)) {
        errors.value.phone = "手机号格式不正确";
        valid = false;
      }

      return valid;
    };

    // 重置表单
    const resetForm = () => {
      editUser.value = { id: null, owner_id: "", name: "", password: "", role_id: "", phone: "", floor: null, room_count: null };
      errors.value = {};
    };

    // 监听角色变化，重置相关字段和错误
    watch(() => editUser.value.role_id, (newRole) => {
      if (newRole !== 2) {
        editUser.value.floor = 0;
        editUser.value.room_count = 0;
        delete errors.value.floor;
        delete errors.value.room_count;
      }
    });

    onMounted(fetchData);

    return {
      users,
      searchQuery,
      filteredUsers,
      dialogMode,
      editUser,
      fetchData,
      showModal,
      closeModal,
      handleEditUser,
      submitAddUser,
      submitEditUser,
      handleDeleteUser,
      validateForm,
      resetForm,
      errors,
      userModalRef,
      openAddUserModal
    };
  },
};
</script>

<style scoped>
.user-management {
  background: #fff;
  padding: 20px;
  border-radius: 5px;
}

.table thead th {
  vertical-align: middle;
}

.text-danger {
  font-size: 0.875em;
}

.modal-content {
  border-radius: 10px;
}

.modal-header {
  background-color: #007bff;
  color: white;
}

.btn-primary {
  background-color: #007bff;
  border-color: #007bff;
}
</style>
